package com.fbinggun.fbinggunutil.statistics;

import com.alibaba.fastjson.JSONObject;
import com.fbinggun.fbinggunutil.FBinggunUtil;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
//统计信息管理库
public class StatisticsProject {

   public Map<String,StatisticsInfo> map=new HashMap<>();
    private final String projectName="StatisticsProject_FBinggun";

    protected StatisticsProject() {
        map=getAllProject();
    }

    private Map<String,StatisticsInfo> getAllProject(){
        Map<String,StatisticsInfo> map1 = new HashMap<String,StatisticsInfo>();
        try {
            JSONObject json= FBinggunUtil.plugin.getStatistMain().getStatisticsTable().getJSONObject(projectName);
            if(json==null){
                return new HashMap<>();
            }
            JSONObject jsonData = json.getJSONObject("Info");
            if(jsonData!=null){
                for(String id: jsonData.keySet()){
                    JSONObject infoData = jsonData.getJSONObject(id);
                    StatisticsInfo info= StatisticsInfo.getInstance(id,infoData);
                    if(info!=null){
                        map1.put(id,info);
                    }
                }
            }

        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return map1;
    }


    //获取信息
    public StatisticsInfo getStatisticsInfo(String id) {
        return map.get(id);
    }
    //创建信息
    public void createInfo(String id,StatisticsInfo info) {
                map.put(id,info);
                save();
    }



    protected JSONObject toJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Player",projectName);
        JSONObject dataJson= new JSONObject();
        for(StatisticsInfo statisticsInfo:map.values()){
            dataJson.put(statisticsInfo.id,statisticsInfo.toJson());
        }

        if(!dataJson.isEmpty()){
            jsonObject.put("Info",dataJson);
            return jsonObject;
        }
        return null;
    }



    protected void save(){
        JSONObject json = toJson();
        if(json==null){
            try {
                FBinggunUtil.plugin.getStatistMain().getStatisticsTable().delJson(projectName);
            } catch (SQLException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                FBinggunUtil.plugin.getStatistMain().getStatisticsTable().setJson(projectName,toJson());
            } catch (SQLException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
